#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <unordered_map>
#include <functional>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <wait.h>
#include <signal.h>
#include <unistd.h>
#include "Log.hpp"
#include "nocopy.hpp"
#include "Comm.hpp"
#include "ThreadPool.hpp"
#include "InetAddr.hpp"

const static int default_backlog = 5;
using callback_t = std::function<void(int, InetAddr&)>;

using task_t = std::function<void()>;

// class TcpServer;

// class ThreadData
// {
// public:
//     ThreadData(int sock, TcpServer *ptr)
//         : _sockfd(sock), _svr_ptr(ptr)
//     {
//     }

//     int Sockfd() { return _sockfd; }
//     TcpServer *GetServer() { return _svr_ptr; }

//     ~ThreadData()
//     {
//         close(_sockfd);
//     }

// private:
//     int _sockfd;
//     TcpServer *_svr_ptr;
// };

class TcpServer : public nocopy
{
public:
    TcpServer(uint16_t port)
        : _port(port), _isrunning(false)
    {}

    void Init()
    {
        // 1. 创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0); // 创建TCP套接字
        if (_listensockfd < 0)
        {
            lg.LogMessage(Fatal, "create socket errror, errno code: %d, error string: %s\n", errno, strerror(errno));
            exit(Socket_Err);
        }
        lg.LogMessage(Debug, "create socket success, sockfd: %d\n", _listensockfd);

        // 固定写法：解决一些少量绑定失败的问题 -- 后面讲到底层原理时再详细解释（这里要解决一个问题：服务端主动断开连接，再启动时bind失败的问题）
        int opt = 1;
        setsockopt(_listensockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

        // 2. 填充本地网络信息，并绑定
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(_listensockfd, (struct sockaddr *)&local, sizeof(local)))
        {
            lg.LogMessage(Fatal, "bind error, errno code: %d, error string: %s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
        lg.LogMessage(Debug, "bing socket success, sockfd: %d\n", _listensockfd);

        // 3. 设置socket为监听状态，TCP特有
        if (listen(_listensockfd, default_backlog)) // 第二个参数先不解释
        {
            lg.LogMessage(Fatal, "Listen socket error, errno code: %d, errror string: %s\n", errno, strerror(errno));
            exit(Listen_Err);
        }
        lg.LogMessage(Debug, "listen socket success, sockfd: %d\n", _listensockfd);

        ThreadNs::ThreadPool<task_t>::GetInstance()->Start();
        // 先将默认服务添加进注册表
        _regis.insert(std::make_pair("default", std::bind(&TcpServer::DefaultService, this, std::placeholders::_1, std::placeholders::_2)));
    }

    void Register(std::string str, callback_t func)
    {
        _regis[str] = func;
    }

    void DefaultService(int sockfd, InetAddr addr)
    {
        lg.LogMessage(Debug, "%s select %s success, fd: %d\n", addr.PrintDebug().c_str(), "default", sockfd);
        (void)addr;
        std::string table = "service list: \n\t |";
        for (auto k : _regis)
        {
            table += k.first;
            table += "|";
        }

        write(sockfd, table.c_str(), table.size());
    }

    void Router(int sockfd, InetAddr addr)
    {
        _regis["default"](sockfd, addr);    // 先执行一下默认服务，显示服务列表
        char buffer[1024];
        ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
        buffer[n] = 0;
        if(n > 0)
        {
            for(auto &k: _regis)
            {
                if(k.first == buffer)
                {
                    std::string outbuffer = "service on";
                    write(sockfd, outbuffer.c_str(), outbuffer.size());
                    k.second(sockfd, addr);
                    lg.LogMessage(Info, "%s client quit... sockfd: %d closed\n", addr.PrintDebug().c_str(), sockfd);
                    close(sockfd);
                    return;
                }
            }
            std::string outbuffer = "no find";
            write(sockfd, outbuffer.c_str(), outbuffer.size());
            lg.LogMessage(Info, "%s client quit... sockfd: %d closed\n", addr.PrintDebug().c_str(), sockfd);
            close(sockfd);
        } 
    }

    // TCP 连接可以进行全双工通信
    // void Service(int sockfd)
    // {
    //     char buffer[1024];
    //     ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
    //     if (n > 0)
    //     {
    //         buffer[n] = 0;
    //         for (auto &k : _regis)
    //         {
    //             if (k.first == buffer)
    //                 ThreadNs::ThreadPool<call_back>::GetInstance()->Push(std::bind(k.second, sockfd, buffer));
    //         }

    //         char outbuffer[] = "unkonw service";
    //         write(sockfd, outbuffer, sizeof(outbuffer));
    //     }
    //     else if (n == 0) // 网络中，read如果返回值是0，表示读到了文件结尾（对端关闭了链接！）
    //     {
    //         lg.LogMessage(Info, "client quit...\n");
    //     }
    //     else
    //     {
    //         lg.LogMessage(Error, "read socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
    //     }
    // }

    // static void *HandlerRequest(void *args)
    // {
    //     pthread_detach(pthread_self()); // 分离线程
    //     ThreadData *td = static_cast<ThreadData *>(args);
    //     td->GetServer()->Service(td->Sockfd());
    //     delete td;
    //     return nullptr;
    // }

    void Start()
    {
        _isrunning = true;
        // signal(SIGCHLD, SIG_IGN); // v3 在Linux环境中，如果对SIGCHLD进行忽略，子进程退出时，自动释放自己的资源
        while (_isrunning)
        {
            // 4. 获取链接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                lg.LogMessage(Warning, "listen socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
                continue;
            }
            lg.LogMessage(Debug, "accept success, get a new sockfd: %d\n", sockfd);

            // 多线程
            // ThreadData *td = new ThreadData(sockfd, this);
            // pthread_t tid;
            // // 主线程和新线程，不需要关闭所谓文件描述符，只需要将线程分离
            // pthread_create(&tid, nullptr, HandlerRequest, td);

            // v5 线程池
            task_t t = std::bind(&TcpServer::Router, this, sockfd, InetAddr(peer));
            ThreadNs::ThreadPool<task_t>::GetInstance()->Push(t);
        }
    }

    ~TcpServer()
    {
        close(_listensockfd);
    }

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning; // 是否启动

    std::unordered_map<std::string, callback_t> _regis; // 注册表
};
